<?php
/**
 *
 * 版权所有：顺势网站管理系统<www.51shunshi.com>

 * 日    期：2015-09-17
 * 版    本：1.0.0
 * 功能说明：后台公用控制器。
 *
 **/

namespace Qwadmin\Controller;

use Common\Controller\BaseController;
use Think\Auth;
use Vendor\Sitemap;

class ComController extends BaseController
{
    public $USER;

    public function _initialize()
    {

        C(setting());
        if (!C("COOKIE_SALT")) {
            $this->error('请配置COOKIE_SALT信息');
        }
        /**
         * 不需要登录控制器
         */
        if (in_array(CONTROLLER_NAME, array("Login"))) {
            return true;
        }
        //检测是否登录
        $flag =  $this->check_login();
        $url = U("login/index");
        if (!$flag) {
            header("Location: {$url}");
            exit(0);
        }
        $m = M();
        $prefix = C('DB_PREFIX');
        $UID = $this->USER['uid'];
        $userinfo = $m->query("SELECT * FROM {$prefix}auth_group g left join {$prefix}auth_group_access a on g.id=a.group_id where a.uid=$UID");
        $Auth = new Auth();
        $allow_controller_name = array('Upload');//放行控制器名称
        $allow_action_name = array();//放行函数名称
        if ($userinfo[0]['group_id'] != 1 && !$Auth->check(CONTROLLER_NAME . '/' . ACTION_NAME,
                $UID) && !in_array(CONTROLLER_NAME, $allow_controller_name) && !in_array(ACTION_NAME,
                $allow_action_name)
        ) {
            $this->error('没有权限访问本页面!');
        }

        $user = member(intval($UID));
        $this->assign('user', $user);


        $current_action_name = ACTION_NAME == 'edit' ? "index" : ACTION_NAME;
        $current = $m->query("SELECT s.id,s.title,s.name,s.tips,s.pid,p.pid as ppid,p.title as ptitle FROM {$prefix}auth_rule s left join {$prefix}auth_rule p on p.id=s.pid where s.name='" . CONTROLLER_NAME . '/' . $current_action_name . "'");
        $this->assign('current', $current[0]);


        $menu_access_id = $userinfo[0]['rules'];

        if ($userinfo[0]['group_id'] != 1) {

            $menu_where = "AND id in ($menu_access_id)";

        } else {

            $menu_where = '';
        }
        $menu = M('auth_rule')->field('id,title,pid,name,icon')->where("islink=1 $menu_where ")->order('o ASC')->select();
        $menu = $this->getMenu($menu);
        $this->assign('menu', $menu);

    }


    protected function getMenu($items, $id = 'id', $pid = 'pid', $son = 'children')
    {
        $tree = array();
        $tmpMap = array();
        //修复父类设置islink=0，但是子类仍然显示的bug @感谢linshaoneng提供代码
        foreach( $items as $item ){
            if( $item['pid']==0 ){
                $father_ids[] = $item['id'];
            }
        }
        //----
        foreach ($items as $item) {
            $tmpMap[$item[$id]] = $item;
        }

        foreach ($items as $item) {
            //修复父类设置islink=0，但是子类仍然显示的bug by shaoneng @感谢linshaoneng提供代码
            if( $item['pid']<>0 && !in_array( $item['pid'], $father_ids )){
                continue;
            }
            //----
            if (isset($tmpMap[$item[$pid]])) {
                $tmpMap[$item[$pid]][$son][] = &$tmpMap[$item[$id]];
            } else {
                $tree[] = &$tmpMap[$item[$id]];
            }
        }
        return $tree;
    }

    public function check_login(){
        session_start();
        $flag = false;
        $salt = C("COOKIE_SALT");
        $ip = get_client_ip();
        $ua = $_SERVER['HTTP_USER_AGENT'];
        $auth = cookie('auth');
        $uid = session('uid');
        if ($uid) {

            $user = M('member')->where(array('uid' => $uid))->find();

            if ($user) {
                if ($auth ==  password($uid.$user['user'].$ip.$ua.$salt)) {
                    $flag = true;
                    $this->USER = $user;
                }
            }
        }

        return $flag;
    }


    /**
     * 导出csv
     * @author fengchen@usuretech.com
     * @time 2016/10/11
     */
    public function exporttocsv($data,$filename,$head){

        $header = implode("\",\"",array_values($head));
        $header = "\"" .$header;
        $header .= "\"\r\n";
        $content = '';
        $content .= $header;

        header("Expires: ".gmdate("D, d M Y H:i:s")." GMT");
        header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
        header("X-DNS-Prefetch-Control: off");
        header("Cache-Control: private, no-cache, must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");

        header("Content-Type: application/octet-stream");
        header("Content-Type: application/force-download");
        header("Content-Disposition: attachment; filename=".iconv("UTF-8","GB2312//IGNORE",$filename).".csv");

        $content = iconv("UTF-8","GB2312//IGNORE",$content);
        echo $content;
        if($data){
            foreach($data as $val){
                $content = "";
                $new_arr = array();
                foreach ($val as $key => $value)
                {
                    if(empty($value)){
                        $value = " ";
                    }
                    array_push($new_arr, preg_replace("/\"/","\"\"",$value));
                }
                $line = implode("\",\"",$new_arr);
                $line = "\"" .$line;
                $line .= "\"\r\n";

                $content .= $line;
                $content = iconv("UTF-8","GB2312//IGNORE",$content);
                echo  $content;
            }
        }
        exit();
    }

    /**
     * 生成网站地图
     * @return bool
     */
    protected function sitemap(){
        $setting=M("setting")->where(array('k'=>'url'))->find();
        //var_dump($setting);exit;
        $url=$setting['v'];
        // 删除原来的网站地图
        unlink("sitemap.xml");
        // 开始生成新的网站地图
        $site = new Sitemap();
        // 网站首页
        $site->AddItem($url, 0);
        // 标签页
        $site->AddItem($url.'/tags.html', 1);
        // 网站栏目
        $category = M('category')->field(array('id','dir'))->select();
        if(!empty($category)){
            foreach ($category as $v){
                $site->AddItem($url.'/'.$v['dir'].'.html', 1);
            }
        }
        // 网站文章
        $article_db = M("article as a");
        $prefix = C('DB_PREFIX');
        $field = "a.aid,{$prefix}category.dir";
        $articles = $article_db
            ->field($field)
            ->order("aid desc")
            ->join("{$prefix}category ON {$prefix}category.id = a.sid")
            ->select();
        if(!empty($articles)){
            foreach ($articles as $v){
                $site->AddItem($url.'/'.$v['dir'].'/'.$v['aid'].'.html', 2);
            }
        }
        $site->SaveToFile('sitemap.xml');
        $bool = file_exists("sitemap.xml");
        return $bool;

    }

    /**
     * 向百度提交文章链接
     * @param $link array
     */
    protected function pushLink($link){
        $setting=M("setting")->where(array('k'=>'url'))->find();
        $url=$setting['v'];
        $set=M("setting")->where(array('k'=>'token'))->find();
        $token=$set['v'];
        if(!is_array($link)){
            return ["code"=>400, "msg"=>"链接以数组格式传入"];
        }
        $api = 'http://data.zz.baidu.com/urls?site='.$url.'&token='.$token;
        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => $api,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $link),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        $obj = json_decode($result);
        if($obj->success > 0){
            //return ["code"=>200, "num"=>$obj->success];
            return ["code"=>200, "num"=>$result];
        }else{
            return ["code"=>400, "num"=>0];
        }

    }

    //文章推送

    protected function artpushFun($aid){
        $setting=M("setting")->where(array('k'=>'url'))->find();
        $url=$setting['v'];
        $pushlogs_DB = M("push_logs");
        $prefix = C('DB_PREFIX');
        $dir = M("article as a")->where('aid=' . $aid)->join("{$prefix}category ON {$prefix}category.id = a.sid")->field("{$prefix}category.dir")->select();
        $urls = array(
            $url."/".$dir['0']["dir"]."/".$aid.".html"
        );
        $RETURN=$this->pushLink($urls);
        //百度推送日志写入数据库
        $data["callback"] = $RETURN['num'];
        $data["aid"] = $aid;
        $data["time"] = date("Y-m-d H:i:s",time());
        if(!empty($RETURN)){
            $data["status"] = 1;
            $pushLogs = $pushlogs_DB->add($data);
        }else{
            $data["status"] = 2;
            $pushLogs = $pushlogs_DB->add($data);
        }
        return $RETURN;
    }

        //上传技术文档


}